package com.hfjyz.registration.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;

import com.hfjyz.registration.command.AnnouncementListCommand;
import com.hfjyz.registration.contants.ExamContants;
import com.hfjyz.registration.model.Exam;
import com.hfjyz.registration.service.AnnouncementService;

public class AnnouncementSelectController extends SimpleFormController {

	private AnnouncementService announcementService;

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.springframework.web.servlet.mvc.AbstractWizardFormController#
	 * referenceData(javax.servlet.http.HttpServletRequest, java.lang.Object,
	 * org.springframework.validation.Errors, int)
	 */
	@SuppressWarnings("rawtypes")
	@Override
	protected Map referenceData(HttpServletRequest request, Object command,
			Errors errors) throws Exception {
		AnnouncementListCommand cmd = (AnnouncementListCommand) command;
		String actionURL = request.getParameter("actionURL");
		if (actionURL == null) {
			actionURL = (String) request.getAttribute("actionURL");
		}
		if (actionURL == null) {
			actionURL = "announcementDetail.action";
		}
		cmd.setActionURL(actionURL);

		request.getSession()
				.removeAttribute(ExamContants.SESSION_KEY_EXAM_INFO);
		return announcementService.initExamSelect(cmd, errors);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		AnnouncementListCommand cmd = (AnnouncementListCommand) command;
		Map model = errors.getModel();
		Exam exam = announcementService.examSelect(request, response, cmd,
				errors);
		if (exam != null) {
			request.getSession().setAttribute(
					ExamContants.SESSION_KEY_EXAM_INFO, exam);
		}
		if (errors.hasErrors()) {
			return new ModelAndView(getFormView(), model);
		}
		String actionURL = cmd.getActionURL();
		if (actionURL == null || actionURL.length() == 0) {
			announcementService.initExamSelect(cmd, null);
			return new ModelAndView(getFormView(), model);
		}
		if (actionURL.charAt(0) == '/') {
			actionURL = actionURL.substring(1);
		}
		RedirectView rv = new RedirectView(actionURL);
		rv.setExposeModelAttributes(true);
		model.putAll(request.getParameterMap());
		return new ModelAndView(rv, model);
	}

	public AnnouncementService getAnnouncementService() {
		return announcementService;
	}

	public void setAnnouncementService(AnnouncementService announcementService) {
		this.announcementService = announcementService;
	}

}